<?php
/**
 * 原点 2020年8月13日08:55:47 拼团操作
 */

namespace app\index\model;

use app\common\controller\SMS;
use app\common\controller\Statistics;
use app\common\lib\Redis;
use app\common\model\Account;
use app\common\model\Logs;
use app\common\model\Rec;
use think\Db;
use think\Model;
use app\common\controller\Base as B;
use Config;
use app\common\model\User;

class Group extends Model
{
    protected $name = 'order_group';
    protected $redis;

    public function __construct($data = [])
    {
        parent::__construct($data);
        $this->redis = Redis::Instance();

    }
        //is_one  1是开团人2跟团人
    /**
     * [generate_group description]
     * @param  [type] $u_id       [description]
     * @param  [type] $goods      [description]
     * @param  [type] $pay_way    [description]
     * @param  [type] $cash  [description]
     * @param  [type] $address_id [description]
     * @param  [type] $group_score       [拼团积分金额]
     * @param  [type] $service_amount      [手续费]
     * @param  [type] $is_one     [description]
     * @return [type]             [description]
     */
    public function generate_group($user, $goods, $pay_way,$address_id,$cash,$remark,$address)
    {
        $this->startTrans();
        $time=time();
        try {
            $sn = date('YmdHis') . $user['id'] . 'G';
            //1.新增拼团记录
            $id = $this->insertGetId([
                'sn' => $sn,
                'uid' => $user['id'],
                'code' => $user['code'],
                'mobile' => $user['tel'],
                'nickname' => $user['name'],
                'pay_way' => $pay_way,
                'address_id' => $address_id,
                'name'              => $address['name'],
                'phone'              => $address['tel'],
                'address'              => $address['sca_name'].$address['address'],
                'product_id' => $goods['id'],
                // 'parent' => $parent_id,
                // 'pay_time' => $time,
                'num'=>$goods['num']?$goods['num']:1,
                // 'frequency' => $goods['frequency'],
                'group_cate_id' => $goods['category1'],
                'amount' => $cash,
                'remark' => $remark,
                'create_time' =>$time,
                'create_date'=>date('Y-m-d',$time)
            ]);
            //将参团会员放入集合中
            // $res=$this->redis->sAdd('g_user'.$goods['id'].'_'.$parent_id,$u_id.'_'.$id);
            $this->commit();
            return ['code' => 1, 'id' => $id, 'sn' => $sn];
        } catch (\Exception $e) {
            die;
            $this->rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public function clear_redis()
    {
        try {
            Redis::Instance()->del('down_order');
            Redis::Instance()->del('center_order');
            Redis::Instance()->del('up_order');
            Redis::Instance()->del('group');
            Logs::adds('后台', '管理员', '初始化');
            return json(['code' => 1, 'msg' => '操作成功']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

    }

    /** 原点 2020年9月22日15:44:21 入团 支付*/
    public function join_group($order_id, $user,$pay_way,$goods)
    {
        $group=Redis::Instance()->hGetAll('group');//当前团是否存在
        $oid_arr=[];
        $is_open=0;
        $inv=$group['inv'];
        Db::startTrans();
        try {
            $time=time();
            $order = parent::get($order_id);
            //1.更改相关状态，扣除余额
            if ($pay_way =='balance') {
                $res=Account::add($user['id'], $pay_way,$order['amount'],  '购买商品', '-',$order_id);
                if (!$res) {
                    Db::rollback();
                    return ['code' => -1, 'msg' => '扣款失败'];
                }
            }
             //发货单
            $res=Order::generate_group($order, $time,$goods);
            if(!$res){
                return ['code' => -1, 'msg' => '订单生成失败'];
            }
            $down_order=Redis::Instance()->sMembers('down_order');
            $up_order=Redis::Instance()->lrange('up_order',0,-1);
            $rec = new Rec();
             //推荐奖
            $res=$rec->rec_award($user['id'],$order['sn'],$order['amount'],$down_order,$up_order,$group);
            //查询推荐人是否在下方排队
            $order_arr=$this->where(['uid'=>$user['referee_id'],'pay_state'=>2,'is_up'=>0])->value('id');
            if($order_arr && !in_array($order_arr,$up_order)){
                $res=Redis::Instance()->rPush('up_order',$order_arr);
                if(!$res){
                    return ['code' => -1, 'msg' => '排队失败'];
                }
                $up_order=Redis::Instance()->lrange('up_order',0,-1);
                parent::update(['is_up' => 1, 'update_time' => $time], ['id'=>$order_arr]);
                //移除元素
                $res=$this->redis->srem('down_order',$order_arr);
                if(!$res){
                    return ['code' => -1, 'msg' => '支付失败3'];
                }
            }
            //存入底部排队列表
            Redis::Instance()->sAdd('down_order',$order_id);
             //存入中间排队
            Redis::Instance()->sAdd('center_order',$order_id);
            $center_order=Redis::Instance()->sMembers('center_order');
            $group=Redis::Instance()->hGetAll('group');//当前团是否存在
            $oid_arr=[];
            $is_open=0;
            $inv=$group['inv'];
             //自动滑落
            if(!$group && $up_order){
                $res=Redis::Instance()->hSet('group','inv',4);//暂存当
                $oid_arr[]=$up_order[0];
                $res=Redis::Instance()->hSet('group','oid',json_encode($oid_arr));//存入团
                $res=$this->redis->srem('center_order',$up_order[0]);
                $center_order=Redis::Instance()->sMembers('center_order');
                $group=Redis::Instance()->hGetAll('group');//当前团是否存在
                //移除元素
                $res=$this->redis->lPop('up_order');
                if(!$res){
                    return ['code' => -1, 'msg' => '支付失败1'];
                }
                $inv=4;
            }
            if($inv>=1&& $center_order){
                foreach ($center_order as $key => $value) {
                    $inv=$inv-1;
                    Redis::Instance()->hSet('group','inv',$inv);
                    $is_open=$inv<1?1:0;
                    $group_oid_arr[]=$value;
                    //移除元素
                    $res=$this->redis->srem('center_order',$value);
                    if(!$res){
                        return ['code' => -1, 'msg' => '支付失败2'];
                    }
                    if($inv<1){
                        break;
                    }
                }
                $hebing=array_merge(json_decode($group['oid'],true),$group_oid_arr);
                $res=Redis::Instance()->hSet('group','oid',json_encode($hebing));//存入团
            }
            parent::update(['pay_state' => 2, 'pay_time' => $time], ['id' =>$order_id]);//修改订单状态
            Rec::update(['is_group' => 1,'status' => 1], ['new_member_id' =>$user['id']]);
            if($user['is_active']==0){
                User::update(['is_group' => 1, 'is_active' => 1,'user_type'=>2], ['id' => $user['id']]);
            }
            //更新伞下单数
            db('user')->where(['id'=>$user['referee_id']])->setInc('rec_yeji');
            $where['new_member_id']=$user['id'];
            $u_id=$rec->where($where)->column('member_id');
            $yeji=db('user')->where(['id'=>['in',$u_id]])->setInc('team_yeji');
             //检测是否成团
            if($is_open==1){
                // file_put_contents('notify/notify.txt', "开团拉",FILE_APPEND);
                $res=$this->open_group($goods);
                if($res['code']!==1){
                    return ['code' => -1, 'msg' => '开团失败'];
                }
                

            }
            
            Logs::adds($user['id'], $user['name'], '参与拼团');
            //4.清除暂存的支付数据
            Redis::Instance()->hDel('order', $user['code']);
            Redis::Instance()->hDel('order_pay', $user['code']);
            Db::commit();
            return ['code' => 1, 'msg' => '支付成功','order_type'=>1,'is_open'=>$is_open,'user'=>$res['new_user'],'order'=>$res['order_info'],'goods'=>$goods];
        } catch (\Exception $e) {
            file_put_contents('notify.txt', "抛异常:\r\n" . $e->getMessage(), FILE_APPEND);
            Db::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /** 开团操作，一定一定要以最快的速度开团 */
    public function open_group($goods)
    {
        try {
            $group=Redis::Instance()->hGetAll('group');//当前团是否存在
            file_put_contents('notify.txt', "开团团:\r\n" . var_export($group,true),FILE_APPEND);
            $time = time();
            $oid_arr=json_decode($group['oid'],true);
            //更新团开团时间
            $tid=db('order_group_parent')->insertGetId([
                    'number'=>date('YmdHis').mt_rand(10000,99999),
                    'group_cate_id'=>1,
                    'product_id'=>$goods['id'],
                    'create_time'=>$time,
                    'update_time'=>$time,
                    'oid_arr'=>$group['oid'],
                    'state'=>2
                    // 'end_time'=>date('Y-m-d',$time+86400*config('end_day'))
                ]);
            // db('user')->where(['id'=>['in',$oid_arr]])->setInc('team_num');
            $info=parent::all(['id'=>['in',$oid_arr]]);
            $sum=$info[0]['amount']*4;
            parent::update(['is_up' => 3, 'update_time' => $time], ['id'=>$oid_arr[0]]);
            // array_sum(array_column($info,'amount'))
            //团长奖励
            $amount=$sum*config('team_rate');
            // file_put_contents('notify.txt', "团子:\r\n" . var_export($info,true),FILE_APPEND);
            Account::add($info[0]['uid'], 'balance',$amount, '团长奖励','+','',1,'团id'.$tid.'订单'.$group['oid']);
            // foreach ($info as $key => $value) {
            //     // Order::generate_group($value, $time,$goods);
            //     //返本金
            //     Account::create_Inc($value['uid'], $value['amount'], 'bonus', '拼团成功返还本金', '', '+',$value['sn']);
            //     //开奖
            // }
            Redis::Instance()->del('group');
            $user=db('user')->where('id='.$info[0]['uid'])->field('wechat_img,alipay_img,img',true)->find();
            
            // //清除机器人
            // $this->redis->del('group_robot_' . $v['id']);
            return ['code' => 1, 'msg' => '已开奖','new_user'=>$user,'order_info'=>$info[0]];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
   
    public function auto_buy($user,$order,$goods)
    {
         //团长自动复购
        if($user['balance']<$order['amount']){
            Logs::adds($user['code'].'余额不足'.$user['balance']);
        }
        //生成订单
        $address=[
            'name'=>$order['name'],
            'tel'=>$order['phone'],
            'address'=>$order['address'],
        ];
        $res = $this->generate_group($user, $goods, 'balance', $order['address_id'], $order['amount'],'自动复购',$address);
        $result = $this->join_group($res['id'], $user, 'balance',$goods);
        if($result['user']['is_auto']==1 && $result['is_open']==1){
            //自动复购
           $this->auto_buy($result['user'],$result['order'],$result['goods']);
        }
    }

}
